package db

import (
	"errors"

	"github.com/astaxie/beego/orm"
    _ "github.com/lib/pq"
)

func init() {
	// PostgreSQL 配置
    orm.RegisterDriver("postgres", orm.DRPostgres) // 注册驱动
    orm.RegisterDataBase("default", "postgres", "user=my_user password=password123 dbname=cricket_apiserver host=127.0.0.1 port=5432 sslmode=disable")
}

func GetOrCreatePerson(personId int64, personName string) (*Person, error) {
	o := orm.NewOrm()
	o.Using("default")

	// 查询用户
    person := Person{PersonId:personId, PersonName:personName}

    _, _, err := o.ReadOrCreate(&person, "PersonName")
    if err == orm.ErrNoRows {
	    return nil, errors.New("查询不到")
	} else if err == orm.ErrMissPK {
	    return nil, errors.New("找不到主键")
	} else {
	    return &person, nil
	}
}